import fetch from 'fermionjs/lib/fetch';
import urlPathConcat from '@kuiper-helpers/url-path-concat/dist';

import pkg from '../../../package.json';
import errorCodesBuilder from '../helpers/errorCodesBuilder';
import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../common/constants';

const errorCodes = errorCodesBuilder();

export function getVulPluginList() {
	const {
		log,
		app: {
			config: {
				[pkg.name]: { serviceApi, token },
			},
		},
	} = this;

	const api = urlPathConcat(serviceApi, '/api/v2/vulndb/kb_vulns');
	log.debug({ api }, '请求漏洞插件列表');

	return fetch(api, {
		headers: { cookie: `token=${token}` },
	})
		.then(resp => {
			return resp.data.map(x => ({
				id: x.source_id,
				label: x.name.zh_cn,
				category: 'file_upload',
				taskType: 'vul',
			}));
		})
		.catch(err => {
			const error = errorCodes['[0E]请求漏洞插件列表失败'].from(err);
			log.error({ api, error }, error.rawMessage);
			throw error;
		});
}

export function getVulPluginCategory() {
	const {
		log,
		app: {
			config: {
				[pkg.name]: { serviceApi, token },
			},
		},
	} = this;

	const api = urlPathConcat(serviceApi, '/api/v2/vulndb/kb_vulns/vuln_types');
	log.debug({ api }, '请求漏洞插件类别列表');

	return Promise.race([
		new Promise(resolve =>
			setTimeout(() => resolve(WARNING_CATEGORY_KEY_LABEL_MAP.vul), 100)
		),
		fetch(api, { headers: { Cookie: `token=${token}` } })
			.then(resp => {
				WARNING_CATEGORY_KEY_LABEL_MAP.vul = resp.reduce((obj, x) => {
					obj[x.en_us] = x.zh_cn;
					return obj;
				}, {});
				return WARNING_CATEGORY_KEY_LABEL_MAP.vul;
			})
			.catch(err => {
				const error = errorCodes['[0E]请求漏洞插件类别列表失败'].from(err);
				log.error({ api, error }, error.rawMessage);
				return WARNING_CATEGORY_KEY_LABEL_MAP.vul;
			}),
	]);
}
